<?php
namespace App\Common\Lib\Com;

use App\Common as com;
use App\Common\Lib\Com\Monitor as nameMonitor;

class Monitor extends com\Cla\ClaBase\CommonOfId\Main {

	private $_watchIndex = 0;

	/**
	 * @var nameMonitor\Watch[][][]
	 */
	protected $watchLists = [];

	/**
	 * @param int $watchId
	 * @return nameMonitor\Watch
	 */
	private function newWatch( int $watchId ):nameMonitor\Watch {
		return new nameMonitor\Watch( $this->dataStore, $watchId );
	}

	/**
	 * 增加监听器
	 * @param string $nameSpace
	 * @param string $watchKey
	 * @return nameMonitor\Watch
	 */
	public function addWatch( string $nameSpace, string $watchKey ):nameMonitor\Watch {
		$watchId = $this->getWatchIndex();
		$watch = $this->newWatch( $watchId );
		$this->watchLists[ $nameSpace ][ $watchKey ][] = $watch;
		return $watch;
	}

	/**
	 * 卸载监听器
	 * @param int $watchId 监听器id
	 * @return $this
	 */
	public function unWatchOfId( int $watchId ):self {
		foreach( $this->watchLists as &$nameSpaceLists ){
			foreach( $nameSpaceLists as &$watchKeyLists ){
				foreach( $watchKeyLists as $watchKeyValueKey => $watchKeyValue ){
					if( $watchKeyValue->getWatchId() === $watchId ){
						unset( $watchKeyLists[ $watchKeyValueKey ] );
					}
				} unset( $watchKeyValue );
			} unset( $watchKeyLists );
		} unset( $watchListsValue );
		//
		return $this;
	}

	/**
	 * 广播
	 * @param string $nameSpace
	 * @param string $watchKey
	 * @param $value
	 * @return $this
	 */
	public function inform( string $nameSpace, string $watchKey, $value ):self {
		if( ! empty( $this->watchLists[ $nameSpace ][ $watchKey ] ) ){
			foreach( $this->watchLists[ $nameSpace ][ $watchKey ] as $watchValue ){
				$watchValue->inform( $value );
			}
		}
		//
		return $this;
	}

	/**
	 * @return int
	 */
	private function getWatchIndex(  ):int {
		return $this->_watchIndex++;
	}


}
